package edu.ucsd.ccdb.tagPopup;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.SQLException;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import edu.ucsd.irods.SQLDBQuery;

public class NoteTab extends JPanel implements ActionListener, KeyListener {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private JTextArea textArea;
	private String file_path;
	private JScrollPane scrollPane;
	private boolean borderCreated;
	private JLabel descriptionLabel ;
	
	public NoteTab ( String file_path ) {
		
		this.file_path = file_path;
		borderCreated = false;
		
		descriptionLabel = new JLabel( "Status: Ready" );
		descriptionLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
		
		textArea = new JTextArea( );
//		textArea.setAlignmentX(LEFT_ALIGNMENT);
		scrollPane = new JScrollPane( textArea );
		textArea.addKeyListener(this);
		try {
			textArea.setText( SQLDBQuery.getNoteCCDBFile(file_path) );
		} catch (SQLException e) {
			e.printStackTrace();
		}
		scrollPane.setAlignmentX(LEFT_ALIGNMENT);
		
		JPanel wrapperPane = new JPanel();
		wrapperPane.setLayout(new BoxLayout(wrapperPane, BoxLayout.Y_AXIS));
		wrapperPane.setAlignmentX(CENTER_ALIGNMENT);
		wrapperPane.add(descriptionLabel);
		wrapperPane.add(Box.createVerticalStrut(3));
		wrapperPane.add(scrollPane);
		
		JButton addNoteButton = new JButton("Add/Update note");
		addNoteButton.addActionListener(this);
		addNoteButton.setAlignmentX(CENTER_ALIGNMENT);
		
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		
		setBorder(BorderFactory.createEmptyBorder( 3,3,3,3 ));
		add(wrapperPane);
		add(Box.createVerticalStrut(3));
		add(addNoteButton);
	}

	public void actionPerformed(ActionEvent e) {
		
		try {
			// TODO wrong when the ccdb_file is not on database already
			SQLDBQuery.manageInsertNodeCCDB (file_path, textArea.getText());
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		
		// reset the border notification
		scrollPane.setBorder(null);
		borderCreated = false;
		
		// set the status
		descriptionLabel.setText("Status: Saved. Ready");
	}

	public void keyPressed(KeyEvent e) {
		
		if (!borderCreated) {
			scrollPane.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(Color.RED), scrollPane.getBorder() ) );
			borderCreated = true;
			
			descriptionLabel.setText("Status: Editing. Click\"Add\\Update note\" to save.");
		}		
	}

	public void keyReleased(KeyEvent e) {
	}

	public void keyTyped(KeyEvent e) {
	}
}
